<script setup>
import memberApi from '@/api/memberApi'
import {reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'

const formatBalance = (row) => {
  // 若 balance 是 null/undefined，兜底为 0
  const safeBalance = row.balance ?? 0; 
  return '￥' + safeBalance.toFixed(2);
};

const members = ref([])
const pageInfo = ref({
    page:1,
    limit:10,
    total:0
})

loadMembers()

function loadMembers() {
    //pageInfo是ref创建的响应式数据容器，此时pageInfo 并不是直接指向{page,limit,total}这个对象，而是一个Ref包装对象，而memberApi.search()方法需要的是普通的JavaScript对象作为参数
    memberApi.search(pageInfo.value).then(result=>{
        console.log("会员分页数据列表：",result)
        //跟后端交互成功
        if(result.code == 200) {
            members.value = result.data.list
            pageInfo.value.total = result.data.total
        } else {
            // ElMessage.error("1服务器忙，请稍后再试")
        }
    }).catch(error=>{
        // ElMessage.error("2服务器忙，请稍后再试")
    })
}

//条件查询
function onSearch() {
    //重置分页状态，确保新的搜索结果从第一页开始展示
    pageInfo.value.page = 1
    loadMembers()
}

const addVisible = ref(false)
const addMember = ref({})
//显示添加弹框
function showAdd() {
    addVisible.value = true
}

//添加会员
function handleAdd() {
    memberApi.add(addMember.value).then(result=>{
        if(result.code == 200) {
            //添加成功
            addVisible.value = false
            ElMessage.success('添加会员成功')
            //重置，清空表单数据，下次添加时表单为空白
            addMember.value = {}//ai的建议
            // addMember.value = ref({})//老师提供的，ai：重置逻辑有误（ref嵌套），会导致后续表单绑定异常
            loadMembers()
        } else {
            //添加失败
            addVisible.value = false
            ElMessage.error(result.msg)
            addMember.value = {}
        }
    }).catch(error=>{
        ElMessage.error('服务器忙，添加会员失败');
    })
}


const editVisible = ref(false)
const editMember = ref({})
//显示编辑弹框
function showEdit(row) {
    editVisible.value = true
    // 对row对象进行深拷贝，并将拷贝后的新对象赋值给editMember.value
    // .stringify：把row对象序列化转换成JSON格式的字符
    // .parse：JSON字符串重新解析为一个新的JavaScript对象
    // JavaScript中对象是引用类型，若editMember.value = row则两者指向同一个内存地址，此时修改editMember.value的属性，会直接影响到原始的row对象
    // 这种深拷贝方式只适用于可被JSON序列化的对象，若包含特殊类型（函数、正则、Date、循环引用等），可能会导致数据丢失或异常
    editMember.value = JSON.parse(JSON.stringify(row))
    // 不显示密码
    editMember.value.password = ''
}

//编辑会员信息
function handleEdit() {
    memberApi.edit(editMember.value).then(result=>{
        if (result.code == 200){
            //修改成功
            editVisible.value = false
            loadMembers()
            //清空编辑框
            editMember.value = {}
            ElMessage.success('编辑会员成功')
        } else {
            editVisible.value = false
            ElMessage.error(result.msg)
            loadMembers()
        }
    }).catch(error=>{
        ElMessage.error('服务器忙，修改失败')
    })
}

//删除会员信息
function handleRemove(row) {
    ElMessageBox.confirm(
        '您确定要删除该信息吗？',
        '删除会员',
        {
            confirmButtonText: '确认',
            cancelButtonText:'取消',
            type:'warning'
        }
    ).then(()=>{
        //点击了确认按钮  
        memberApi.remove(row.id).then(result=>{
            if(result.code == 200){
                //删除成功
                loadMembers()
                ElMessage.success('删除会员成功')
            } else {
                //删除失败
                loadMembers()
                ElMessage.error(result.msg)
            }
        }).catch(error=>{
            ElMessage.error('服务器忙，删除会员失败')
        })
    }).catch(()=>{
        //取消操作
    })
}
</script>

<template>
    <div class="content">
        <!-- 搜索栏 -->
        <!-- :model="表单数据模型绑定pageInfo对象"；:inline="true"设置表单为行内模式，表单项横向排列 -->
        <el-form :model="pageInfo" :inline="true">
            <el-form-item label="名字" :label-width="60">
                <!-- v-model="双向数据绑定"；placeholder="输入框提示文本" -->
                <el-input v-model="pageInfo.name" placeholder="请输入会员名字"/>
            </el-form-item>
            <el-form-item label="电话" :label-width="60">
                <el-input v-model="pageInfo.phone" placeholder="请输入会员电话"/>
            </el-form-item>
            <!-- 搜索按钮，绑定点击事件 -->
            <el-form-item>
                <el-button type="primary" @click="onSearch"><el-icon><Search></Search></el-icon></el-button>
            </el-form-item>
        </el-form>
        <!-- 创建按钮 -->
        <div class="bar">
            <!-- 绑定点击事件，显示添加会员的表单 -->
            <el-button type="success" @click="showAdd">创建会员</el-button>
        </div>
        <!-- 会员列表展示 -->
        <!-- :data="表格数据源为members数组"；:stripe="true"表格斑马条纹样式；:border="true"显示表格边框 -->
        <el-table :data="members" :stripe="true" :border="true" style="width: 100%">
            <!-- prop="指定对应数据中的id字段"；label="列标题" -->
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="phone" label="手机号" width="180" />
            <el-table-column prop="name" label="名字" />
            <!-- :formatter指定格式化函数，将余额转换为带人民币符号的两位小数格式 -->
            <el-table-column prop="balance" label="余额" :formatter="formatBalance" />
            <!-- <el-table-column prop="balance" label="余额" :formatter="row=>'￥'+row.balance.toFixed(2)"/> -->
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="315">
                <!-- 作用于插槽，自定义列内容；scope.row：当前行的数据对象 -->
                <template #default="scope">
                    <!-- <el-button size="small" type="primary"
                        @click="showEdit(scope.row)"><el-icon><ShoppingTrolley/></el-icon>&nbsp;消费</el-button> 
                    <el-button size="small" type="warning"
                        @click="showEdit(scope.row)"><el-icon><Money/></el-icon>&nbsp;充值</el-button>  -->
                    <!-- 触发编辑 -->
                    <el-button size="small" type="success"
                        @click="showEdit(scope.row)"><el-icon><edit/></el-icon>&nbsp;编辑</el-button> 
                    <!-- 触发删除 -->
                    <el-button size="small" type="danger"
                        @click="handleRemove(scope.row)"><el-icon><delete/></el-icon>&nbsp;删除</el-button> 
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- v-model:current-page="双向绑定当前页码" v-model:page-size="双向绑定每条页数" 
        :total="设置总记录数" :page-sizes="设置可选的每页条数" :background="为分页按钮添加背景色"
        layout定义分页组件的布局和显示顺序 @change="页码或每页条数变化时触发方法加载数据" -->
        <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
            :total="pageInfo.total" :page-sizes="[10, 20, 50, 100]" :background="true"
            layout="total, sizes, prev, pager, next, jumper" @change="loadMembers" />
    </div>

    <!-- 添加的弹窗 -->
    <el-dialog v-model="addVisible" title="创建新会员" width="500">
        <el-form :model="addMember">
            <el-form-item label="名字" :label-width="60">
                <el-input v-model="addMember.name" placeholder="请输入会员名字"/>
            </el-form-item>
            <el-form-item label="电话" :label-width="60">
                <el-input v-model="addMember.phone" placeholder="请输入会员电话"/>
            </el-form-item>
            <el-form-item label="密码" :label-width="60">
                <el-input v-model="addMember.password" show-password placeholder="请输入会员密码"/>
            </el-form-item>
            <el-form-item label="充值" :label-width="60">
                <el-input type="number" v-model="addMember.balance" placeholder="请输入充值金额"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">
                    创建
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑的弹窗 -->
    <el-dialog v-model="editVisible" title="编辑会员" width="500">
        <el-form :model="editMember">
            <el-form-item label="名字" :label-width="60">
                <el-input v-model="editMember.name" placeholder="请输入会员名字"/>
            </el-form-item>
            <el-form-item label="电话" :label-width="60">
                <el-input v-model="editMember.phone" placeholder="请输入会员电话"/>
            </el-form-item>
            <el-form-item label="密码" :label-width="60">
                <el-input v-model="editMember.password" show-password placeholder="请输入会员密码"/>
            </el-form-item>
            <el-form-item label="余额" :label-width="60">
                <el-input v-model="editMember.balance" placeholder="请输入余额"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editVisible = false">取消</el-button>
                <el-button type="primary" @click="handleEdit">
                    编辑
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style >

</style>